import { useState, useEffect } from "react";
import { Form, message, Modal } from "antd";

import request from "@/utils/request";
import { IForm } from "@/components";
import { transformTreeData /*getAllParentIds*/ } from "@/utils/util";
import { useAppSelector } from "@/utils/hooks";

import type { FormItemConfig } from "@/components/FormItem/type";
import { RecordItem, Params } from "../type";
import { roleTypeMap } from "@/utils/consts";

interface Props {
	open: boolean;
	record?: RecordItem;
	onCancel: () => void;
	onSearch: (params: Params) => void;
}

const AddModal: React.FC<Props> = ({ open, onCancel, record, onSearch }) => {
	const [app] = useAppSelector(state => [state.app]);
	const [form] = Form.useForm();
	const [resources, setResources] = useState<DataNode[]>([]);
	const [initialResources, setInitialResources] = useState<string[]>([]);

	useEffect(() => {
		if (open) {
			// queryResources()
		}
	}, [open]);

	const queryResources = (value?: string) => {
		const data = {
			roleType: value,
			tenantId: app.currentEntity.entityId,
		};
		request("commonQueryResourcesByEntity", { data }).then(res => {
			if (res?.code === 0) {
				setResources((res.data));
			}
		});
	};

	const queryInitialResources = (value: string) => {
		/**
		 * 这个接口需要注意，后端如果返回某个父亲节点，则下面的所以自节点也需要返回
		 * 如果返回了某个父亲节点的所有自节点，那么父亲节点也需要返回
		 */
		request("roleManageInitialResources", { data: { roleId: value } }).then(res => {
			if (res?.code === 0) {
				setInitialResources(res.data);
				form.setFieldsValue({ resourceIds: res.data });
			}
		});
	};

	const handleOk = async () => {
		try {
			const { resourceIds, ...rest } = await form.validateFields();
			// const pIds = getAllParentIds(resources, resourceIds)
			const data = {
				...rest,
				resourceIds: [...resourceIds /*...pIds*/],
				tenantId: app.currentEntity.entityId,
			};
			request("roleManageAdd", { data }).then(res => {
				if (res.code === 0) {
					message.success("添加成功");
					onSearch({} as Params);
					handleCancel();
				}
			});
		} catch (error) {
			message.warn("信息录入有误");
		}
	};

	const handleCancelClick = () => {
		if (record) {
			return handleCancel();
		}
		Modal.confirm({
			title: "提示",
			content: `是否确认取消本次操作？取消后将需要重新操作`,
			onOk() {
				handleCancel();
			}
		});
	};

	const handleCancel = () => {
		form.resetFields();
		setResources([]);
		setInitialResources([]);
		onCancel();
	};

	const formItemsConfig: FormItemConfig[] = [
		{
			type: "roleTypeSelect",
			formItemProps: {
				label: "角色类型",
				name: "roleType",
				rules: [{ required: true }]
			},
			childProps: {
				// mode:"multiple",
				options: [
				  { label: '平台角色', value: roleTypeMap.platformRole },
				  { label: '用户角色', value: roleTypeMap.enterpriseRole },
				],
				onChange(value: string) {
					queryResources(value);
					// queryInitialResources(value)
				}
			}
		},
		{
			type: "input",
			formItemProps: {
				label: "角色名称",
				name: "roleName",
				rules: [{ required: true }, { max: 50 }]
			}
		},
		resources.length
			? {
					type: "tree",
					formItemProps: {
						label: "资源点权限",
						name: "resourceIds",
						valuePropName: "checkedKeys",
						trigger: "onCheck",
						rules: [{ required: true }]
					},
					childProps: {
						defaultExpandAll: true,
						// defaultExpandedKeys: initialResources,
						// onCheck(checked, info) {
						//   //  是否需要携带半选的父亲节点
						// },
						treeData: resources as any
					}
			  }
			: null
	];

	return (
		<Modal
			title="添加角色"
			open={open}
			width={660}
			destroyOnClose
			maskClosable={false}
			onOk={handleOk}
			onCancel={handleCancelClick}
		>
			<IForm layout="vertical" form={form} formItemsConfig={formItemsConfig}></IForm>
		</Modal>
	);
};

export default AddModal;
